package vip.xiaonuo.issued.impl.device;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;
import vip.xiaonuo.facedoor.iservice.IAppVersionService;
import vip.xiaonuo.facedoor.modular.appversion.entity.AppVersion;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.facedoor.rule.RuleConstant;
import vip.xiaonuo.issued.bean.CMD;
import vip.xiaonuo.issued.bean.Topic;
import vip.xiaonuo.issued.inter.MqttGateway;
import vip.xiaonuo.issued.util.SnowIdGen;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

@Service(value = RuleConstant.DW + RuleConstant.APP_UPDATE)
public class MqttAppUpdateService implements IAppVersionService {

    @Resource
    private MqttGateway gateway;

    @Resource
    private DeviceBaseService deviceBaseService;

    @Override
    public void notice(AppVersion version)  {
        List<DeviceBase> devices = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>().eq(DeviceBase::getDeviceType, version.getPlatform()+""));
        for (DeviceBase device : devices) {
            this.notice(device);
        }
    }

    @Override
    public void notice(DeviceBase device) {
        Map<String, Object> baseMap = SnowIdGen.getBaseMap();
        baseMap.put("deviceId", device.getId());
        baseMap.put(CMD.CMD, CMD.UPDATE_APK);
        String req = JSON.toJSONString(baseMap);
        gateway.sendToMqtt(MessageFormat.format(Topic.DEVICE_TOPIC, device.getId()), 1, req);
    }
}
